package com.micro.school.order.utils;

import com.alibaba.nacos.common.packagescan.resource.ClassPathResource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

@Component
public class FileDownloadUtil {

    /**
     * 下载classpath中的文件
     * @param filePath 文件路径（相对于classpath）
     * @param fileName 下载时显示的文件名
     * @param response HTTP响应对象
     * @throws IOException IO异常
     */
    public static void downloadFileFromClasspath(String filePath, String fileName, HttpServletResponse response) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(filePath);
        InputStream inputStream = classPathResource.getInputStream();

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }

    /**
     * 下载Excel模板文件
     * @param templatePath 模板文件路径
     * @param fileName 下载文件名
     * @param response HTTP响应对象
     * @throws IOException IO异常
     */
    public static void downloadExcelTemplate(String templatePath, String fileName, HttpServletResponse response) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(templatePath);
        InputStream inputStream = classPathResource.getInputStream();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.flush();
        inputStream.close();
        outputStream.close();
    }
}
